package com.phantom.reflection;

import java.lang.reflect.Constructor;

/**
 * 演示通过反射机制创建实例
 */
public class ReflectCreateInstance {
    public static void main(String[] args) throws Exception {

        Class<?> userClass = Class.forName("com.phantom.reflection.User");

        User user = (User) userClass.newInstance();
        System.out.println(user);

        Constructor<?> constructor = userClass.getConstructor(String.class);
        User user2 = (User) constructor.newInstance("phantom");
        System.out.println(user2);

        Constructor<?> constructor1 = userClass.getDeclaredConstructor(int.class, String.class);
        constructor1.setAccessible(true);
        User ciel = (User) constructor1.newInstance(18, "Ciel");
        System.out.println(ciel);


    }

}

class User {
    private int age;
    private String name;

    public User() {
    }

    public User(String name) {
        this.name = name;
    }

    private User(int age, String name) {
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}
